const { Forbidden } = require("http-errors");
const jwt = require("jsonwebtoken");
const { fail } = require("../utils/response");
const { User } = require("../models");

const userAuthMiddle = async (req, res, next) => {
  const auth = req.headers["token"];
  const token = auth && auth.split(" ")[1];
  // 验证token,需要jwt密钥，需存到env中
  try {
    if (!token) {
      throw new Forbidden("缺少token");
    }
    const decoded = jwt.verify(token, process.env.JWT_SECKET);
    const user = await User.findByPk(decoded?.userId);
    if (!user) {
      throw new NotFound("用户不存在");
    }
    console.log('middle-decoded', decoded);
    console.log('middle-user', user);
    
    req.user = decoded;
    next();
  } catch (error) {
    console.log("verify ==", error);
    fail(res, error);
  }
};
module.exports = userAuthMiddle;
